package com.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author YZK
 * @Date 2023/10/18
 */
public class HttpUtils {

    /***
     * 获取下载文件大小
     * @param url 文件地址
     * @return 文件大小
     */
    public static long getHttpFileContentLength(String url) throws IOException {
        int contentLength;
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = getHttpURLConnection(url);
            contentLength = httpURLConnection.getContentLength();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return contentLength;
    }

    /***
     * 获取HttpURLConnection链接对象
     * @param url 文件地址
     * @return HttpURLConnection
     */
    public static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL httpURL = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpURL.openConnection();
        //向文件所在的服务器发达标识信息
        httpURLConnection.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Edg/118.0.2088.46");
        return httpURLConnection;
    }

    /***
     *分块下载
     * @param url 文件地址
     * @param startPos 下载文件起始位置
     * @param endPos 下载文件结束位置
     * @return HttpURLConnection
     */
    public static HttpURLConnection getHttpURLConnection(String url, long startPos, long endPos) throws IOException {
        HttpURLConnection httpURLConnection = getHttpURLConnection(url);
        LogUtils.info("下载的区间是：{}-{}", startPos, endPos);
        if (endPos != 0) {
            httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
        } else {
            httpURLConnection.setRequestProperty("Range", "bytes=" + startPos + "-");
        }
        return httpURLConnection;
    }

    /***
     *  获取文件名
     * @param url 文件地址
     * @return 文件名
     */
    public static String getFileName(String url) {
        //找到URL字符串中最后一个斜杠(/)的位置，将其索引值赋给整型变量index。
        int index = url.lastIndexOf("/");
        //从index+1的位置开始截取字符串，即从最后一个斜杠之后的部分开始截取，直到字符串末尾
        return url.substring(index + 1);
    }

}
